package com.blog.service.service;


import com.blog.check.check.CheckResult;
import com.blog.dao.dao.*;
import com.blog.service.constant.SysPropertiesKeyConsts;
import com.blog.until.RandomUtil;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.Properties;

/**
 * 基础服务
 *
 * @author 泡面ing
 * @date 2021/11/17
 */
@Service
public class BaseService {

    /**
     * 依赖注入
     */
    protected SystemDAO systemDAO;
    protected ProfileDAO profileDAO;
    protected UserDAO userDAO;
    protected BlogTypeDAO blogTypeDAO;
    protected BlogDAO blogDAO;
    protected ViewsDAO viewsDAO;
    protected CommentDAO commentDAO;
    protected PictureDAO pictureDAO;

    @Autowired
    public void setSystemDAO(SystemDAO systemDAO){
        this.systemDAO = systemDAO;
    }

    @Autowired
    public  void setUserDAO(UserDAO userDAO){
        this.userDAO = userDAO;
    }

    @Autowired
    public void setProfileDAO(ProfileDAO profileDAO){
        this.profileDAO = profileDAO;
    }

    @Autowired
    public void setBlogTypeDAO(BlogTypeDAO blogTypeDAO){
        this.blogTypeDAO = blogTypeDAO;
    }

    @Autowired
    public void setBlogDAO(BlogDAO blogDAO){
        this.blogDAO = blogDAO;
    }

    @Autowired
    public void setViewsDAO(ViewsDAO viewsDAO){
        this.viewsDAO = viewsDAO;
    }

    @Autowired
    public void setCommentDAO(CommentDAO commentDAO){
        this.commentDAO = commentDAO;
    }

    @Autowired
    public void setPictureDAO(PictureDAO pictureDAO){
        this.pictureDAO = pictureDAO;
    }
    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 储存文件路径的文件的路径
     */
    public static String SYS_PROPERTIES_FILEPATH = File.separator + "etc" + File.separator + "blog" + File.separator
            + "sys.properties";

    public Properties getProperties(String filePath) throws Exception {
        FileSystemResource file = new FileSystemResource(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath + " not found。");
        }
        return PropertiesLoaderUtils.loadProperties(file);
    }
    public Date getTime(){
        return systemDAO.getCurrentSqlDateTime();
    }
    /**
     * 获得用户名
     *
     * @return {@link String}
     */
    public static String getUsername(){
        return (String) SecurityUtils.getSubject().getPrincipal();
    }

    public static String logInfo(CheckResult checkResult) {
        FormattingTuple ft = MessageFormatter.format("[{}] " + checkResult.getMsg(), checkResult.getCode());
        return ft.getMessage();
    }


    /**
     * 得到图像后缀
     *
     * @param base64Prefix base64前缀
     * @return {@link String}
     */
    public String getImageSuffix(String base64Prefix) {
        String suffix = null;
        String jpg = "data:image/jpeg;base64";
        String ico = "data:image/x-icon;base64";
        String png = "data:image/png;base64";
        String gif = "data:image/gif;base64";
        if (StringUtils.equalsIgnoreCase(base64Prefix, jpg)) {
            suffix = ".jpg";
        } else if (StringUtils.equalsIgnoreCase(base64Prefix, ico)) {
            suffix = ".ico";
        } else if (StringUtils.equalsIgnoreCase(base64Prefix, png)) {
            suffix = ".png";
        } else if (StringUtils.equalsIgnoreCase(base64Prefix, gif)) {
            suffix = ".gif";
        }
        return suffix;
    }

    /**
     * 得到图像base64前缀
     *
     * @param file 文件
     * @return {@link String}
     */
    public String getImageBase64Prefix(File file) {
        String prefix = "." + StringUtils.substringAfterLast(file.getName(), ".");
        String jpg = ".jpg";
        String ico = ".ico";
        String png = ".png";
        String gif = ".gif";
        if (StringUtils.equalsIgnoreCase(prefix,jpg)) {
            return "data:image/jpeg;base64";
        } else if (StringUtils.equalsIgnoreCase(prefix, ico)) {
            return "data:image/x-icon;base64";
        } else if (StringUtils.equalsIgnoreCase(prefix, png)) {
            return "data:image/png;base64";
        } else if (StringUtils.equalsIgnoreCase(prefix, gif)) {
            return "data:image/gif;base64";
        }
        return null;
    }

    /**
     * 生成图片名称
     *
     * @param imageName 图片的名字
     * @return {@link String}
     * @throws Exception 异常
     */
    public String makeDestPath(String imageName) throws Exception {
        Properties properties = getProperties(SYS_PROPERTIES_FILEPATH);
        String iconPath = properties.getProperty(SysPropertiesKeyConsts.ICON_PATH);
        if (StringUtils.isBlank(iconPath)){
            logger.error(SysPropertiesKeyConsts.ICON_PATH + " is blank。");
            throw new Exception(SysPropertiesKeyConsts.ICON_PATH + " is blank。");
        }
        String base64Prefix = StringUtils.substringBefore(imageName, ",");
        String suffix = getImageSuffix(base64Prefix);
        Date date = systemDAO.getCurrentSqlDateTime();

        return iconPath + "/" + RandomUtil.getRandomCharAndNum(6) + "_"
                + DateFormatUtils.format(date, "yyyyMMddHHmmss") + suffix;
    }

    /**
     * 获得ip地址
     *
     * @param request 请求
     * @return {@link String}
     */
    public static String getIpAddress(HttpServletRequest request) {
        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if(index != -1){
                return XFor.substring(0,index);
            }else{
                return XFor;
            }
        }
        XFor = Xip;
        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            return XFor;
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }

}
